<template>
  <div class="content">
    <div class="pageSearchViewStock">
      <div class="pageTableMenuViewStock">
        <div class="pageTableTitle" style="position: sticky;top: 0">
          <div>角色信息</div>
        </div>
        <div class="pageTableButViewStock">
          <el-button type="primary" :icon="Plus" size="small" @click="handleAdd()">新建</el-button>
        </div>
      </div>
      <div style="margin-top: 0;height: calc(100vh - 180px);overflow-y: auto">
        <el-tree :data="roleData" node-key="id" default-expand-all :expand-on-click-node="false"
                 :props="{ children: 'sonList' }" :disable-branch-nodes="true" @current-change="handleSearch">
          <template #default="{ node, data }">
            <div class="custom-tree-node">
              <span :class="data.id == rowInfo.id ? 'is-penultimate' : ''">{{ data.name }}</span>
              <span>
							<el-button type="text" @click.stop="append(data, node.level)" :icon="Edit"></el-button>
							<el-button link @click.stop="remove(data)" type="danger" :icon="Delete"></el-button>
						</span>
            </div>
          </template>
        </el-tree>
      </div>
    </div>
    <div class="pageTableView" style="margin-top: 0;height: 100%">
      <div class="pageTableMenuViewStock">
        <div class="pageTableTitle">
          <div>菜单信息</div>
        </div>
        <div class="pageTableButViewStock">
          <el-button type="primary" :icon="Plus" size="small" @click="showAdd()">新建</el-button>
          <el-button type="primary" :icon="Finished" size="small" @click="handleAddStock()">保存</el-button>
        </div>
      </div>
      <div style="margin-top: 0;height: calc(100vh - 180px);overflow-y: auto">
        <el-tree ref="routerRef" :data="routerList" node-key="id" default-expand-all show-checkbox
                 @check-change="handleCheckChange" :default-checked-keys="defaultKeys" :check-strictly="strictly">
          <template #default="{ node, data }">
            <div class="custom-tree-node">
              <span>{{ data.name }}</span>
              <span>
								<el-button type="text" @click="appendShow(data)" :icon="Edit"></el-button>
								<el-button link @click="removeRole(data)" type="danger" :icon="Delete"></el-button>
							</span>
            </div>
          </template>
        </el-tree>
      </div>
    </div>
    <!-- 角色新建 -->
    <el-dialog v-model="roleAdd" title="菜单" width="1000">
      <el-form :model="roleForm" ref="ruleFormRef" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="名称">
              <el-input v-model="roleForm.name" placeholder="菜单名称(title)" style="width: 400px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="path">
              <el-input v-model="roleForm.urlPath" placeholder="path" style="width: 400px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="component">
              <el-input v-model="roleForm.component" placeholder="component" style="width: 400px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="name">
              <el-input v-model="roleForm.code" placeholder="name" style="width: 400px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="indexs">
              <el-input-number v-model="roleForm.indexs" placeholder="indexs" style="width: 400px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上级类目">
              <el-tree-select v-model="roleForm.pid" :data="routerList" label="name" check-strictly
                              filterable :render-after-expand="false" :props="{
									children: 'children',
									label: 'name',
									value: 'id',
								}" style="width: 400px"/>
              <!-- <el-select v-model="roleForm.pid" placeholder="请选择上级类目" clearable style="width: 400px">
                <el-option v-for="(item, index) of roleArray" :key="index" :label="item.name" :value="item.id" />
              </el-select> -->
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="菜单类型">
              <el-select v-model="roleForm.type" placeholder="请选择菜单类型" style="width: 400px">
                <el-option :key="0" label="类目" :value="0"/>
                <el-option :key="1" label="菜单" :value="1"/>
                <el-option :key="2" label="按钮" :value="2"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="isWeb">
              <el-select v-model="roleForm.isWeb" placeholder="请选择isWeb" style="width: 400px">
                <el-option :key="1" label="APP" :value="1"/>
                <el-option :key="0" label="PC" :value="0"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="roleAdd = false">取消</el-button>
          <el-button type="primary" @click="roleAddSum()">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="showCrud" :title="crudTitle + '角色'" width="600">
      <el-form :model="formData" ref="ruleFormRef" :rules="rules" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="角色名称" required prop="name">
              <el-input v-model="formData.name" :placeholder="'请输入角色名称'" style="width: 400px"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleStockSave(ruleFormRef)">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {Delete, Edit, Finished, Plus} from '@element-plus/icons-vue';
import {ElMessage, ElMessageBox, FormInstance, FormRules} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {reactive, ref} from 'vue';
import {useRouter, useRoute} from 'vue-router';

const crudTitle = computed(() => {
  return isEdit.value ? '编辑' : '新建';
});
const router = useRouter();

const routerList = ref([]);

onMounted(() => {
  getRoleData();
  getRoleList();
});
const roleAdd = ref(false);
const roleForm = ref({});
const appendShow = (row) => {
  roleAdd.value = true;
  roleForm.value = row;
};
const showAdd = () => {
  roleAdd.value = true;
  roleForm.value = {};
};

const checkedNodes = ref([]);

interface Tree {
  name: string;
}

const roleArray = ref([]);
const getRoleList = () => {
  axiosInstance.post('/api/basedataRoute/getAll', {}).then(res => {
    if (res.code != 200) {
      ElMessage.error(res.message);
      return false;
    }
    roleArray.value = res.data;
    var pList = [];
    for (const item of res.data) {
      if (item.type == 0) {
        pList.push(item);
      }
    }
    if (pList.length > 0) {
      for (const item of pList) {
        item.children = [];
        for (const items of res.data) {
          if (items.type == 1 && items.pid == item.id) {
            item.children.push(items);
            console.log(items);
          }
        }
      }
    }

    for (const item of pList) {
      for (const items of item.children) {
        items.children = [];
        for (const itemss of res.data) {
          if (itemss.type == 1 && itemss.pid == items.id) {
            items.children.push(itemss);
          }
        }
      }
    }
    routerList.value = pList;
  });
};

const handleCheckChange = (
    data: Tree,
    checked: boolean,
    indeterminate: boolean
) => {
  // 当节点选中或取消选中时，更新 checkedNodes
  if (checked) {
    if (!checkedNodes.value.includes(data)) {
      checkedNodes.value.push(data);
    }
  } else {
    checkedNodes.value = checkedNodes.value.filter(node => node !== data);
  }

};


const ruleFormRef = ref<FormInstance>();

interface RuleForm {
  warehouseName: string;
  warehouseCode: string;
  storageType: string;
  warehouseFrozen: string;
}

const rules = reactive<FormRules<formData>>({
  name: [
    {required: true, message: '请输入角色名称', trigger: 'blur'}
  ]
});

const formData = ref({});
const isEdit = ref(false);//是否编辑
const showCrud = ref(false);//编辑/新建弹框
const strictly = ref(true);//true 勾选父级不会影响子级
// 点击保存库位
const handleStockSave = async (e: FormInstance | undefined) => {
  if (!e) return;
  await e.validate((valid, fields) => {
    if (valid) {
      if (isStockEdit.value) {
        // 编辑
        axiosInstance.put('/api/basedataRole/update', formData.value).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          getRoleData();
          getRoleList();
        });
      } else {
        // 新建
        axiosInstance.post('/api/basedataRole/save', formData.value).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          getRoleData();
          getRoleList();
        });
      }

    }
  });
};

const defaultKeys = ref([]);

// 点击新建
const handleAdd = () => {
  isEdit.value = false;
  formData.value = {};
  showCrud.value = true;
  isStockEdit.value = false;
};

const roleAddSum = () => {
  if (roleForm.value.id) {
    axiosInstance.put('/api/basedataRoute/update', roleForm.value).then(res => {
      if (res.code != 200) {
        ElMessage.error(res.message);
        return false;
      }
      ElMessage.success('操作成功!');
      roleAdd.value = false;
      getRoleList();
      getRoleData();
    });
  } else {
    // roleForm.value
    axiosInstance.post('/api/basedataRoute/save', roleForm.value).then(res => {
      if (res.code != 200) {
        ElMessage.error(res.message);
        return false;
      }
      ElMessage.success('操作成功!');
      roleAdd.value = false;
      getRoleList();
      getRoleData();
    });
  }

};

// 点击编辑仓库
const append = (e) => {
  isEdit.value = true;
  formData.value = JSON.parse(JSON.stringify(e));
  showCrud.value = true;
  isStockEdit.value = true;
};
const isStockEdit = ref(false);
const showStockCrud = ref(false);

// 点击保存
const handleAddStock = () => {
  // checkedNodes.value
  // roleData.value
  const list = [];

// 递归函数检查节点是否匹配
  function checkNode(node, targetPath) {
    if (node.urlPath == targetPath) {
      return true;
    }

    if (node.children && node.children.length > 0) {
      for (const child of node.children) {
        if (checkNode(child, targetPath)) {
          // 如果子节点匹配，将当前节点ID加入列表（如果尚未存在）
          if (!list.includes(node.id)) {
            list.push(node.id);
          }
          return true;
        }
      }
    }
    return false;
  }

// 主循环
  for (const item of checkedNodes.value) {
    for (const ro of routerList.value) {
      // 检查当前路由及其所有子节点
      if (checkNode(ro, item.urlPath)) {
        // 如果匹配，将目标节点ID加入列表
        if (!list.includes(item.id)) {
          list.push(item.id);
        }
      }
    }
  }
  let param = [];
  for (const item of list) {
    param.push({
      roleId: rowInfo.value.id,
      isWeb: 0,
      routeId: item
    });
  }

  axiosInstance.post('/api/basedataRoleRoute/batchSave', param).then(res => {
    if (res.code != 200) {
      ElMessage.error(res.message);
      return false;
    }
    ElMessage.success('操作成功!');
  });

};

// 仓位列表
const roleData = ref([]);

const rowInfo = ref({});
const routerRef = ref<InstanceType<typeof ElTree>>();
const handleSearch = (row) => {
  strictly.value = true;
  defaultKeys.value = [];
  routerRef.value!.setCheckedKeys([], false);
  rowInfo.value = row;
  // param = { warehouseId: row.id, ...pageSearch.value };
  axiosInstance.post('/api/basedataRoleRoute/queryByRoleId', {roleId: rowInfo.value.id})
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        const list = [];
        if (res.data && res.data.length > 0) {
          for (const item of res.data) {
            list.push(item.id);
          }
        }

        defaultKeys.value = list;
        strictly.value = false;
      });

};

const getRoleData = () => {
  axiosInstance.post('/api/basedataRole/getAll', {}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }

    roleData.value = res.data;
    showCrud.value = false;
    showStockCrud.value = false;
    handleSearch(res.data[0]);
  });
};


const removeRole = (e) => {
  ElMessageBox.confirm(
      '确认删除该数据?',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'error'
      }
  )
      .then(() => {
        axiosInstance.delete(`/api/basedataRoute/delete`, {
          data: {
            ids: [e.id]
          }
        })
            .then(res => {
              if (res.code === 200) {
                ElMessage.success('删除成功');
                getRoleList();
              }
            });
      });
};

const remove = (e) => {
  ElMessageBox.confirm(
      '确认删除该数据?',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'error'
      }
  )
      .then(() => {
        axiosInstance.delete(`/api/basedataRole/delete`, {
          data: {
            ids: [e.id]
          }
        })
            .then(res => {
              if (res.code === 200) {
                ElMessage.success('删除成功');
                getRoleData();
              }
            });
      });
};

</script>
<style scoped lang="scss">
.content {
  background: #f9f9f9;
  height: calc(100vh - 105px);
  display: flex;
}

.pageSearchViewStock {
  width: 25%;
  padding: 20px;
  background: #fff;
  border-right: 1px solid #f9f9f9;
}

.pageTableView {
  width: 75%;
  background: #fff;
  border-radius: 10px;
}

.pageTableMenuViewStock {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.pageTableTitleStock {
  font-size: 18px;
}

.pageTableClass {
  width: 100%;
  height: 100%;
  margin: 10px 0;
}

.pagePagination {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding: 0 10px;
}

.pageTableButViewStock {
  height: 40px;
  display: flex;
  align-items: center;
}

.is-penultimate {
  color: #626aef;
  font-weight: 700;
}
</style>
